import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.example.db"
typeMapping = [
        (~/(?i)bigint/)                   : "Long",
        (~/(?i)int/)                      : "Int",
        (~/(?i)tinyint/)                  : "Boolean",
        (~/(?i)float|double|decimal|real/): "BigDecimal",
        (~/(?i)time|datetime|timestamp/)  : "LocalDateTime",
        (~/(?i)date/)                     : "LocalDate",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, className + ".kt").withPrintWriter { out -> generate(out, table.getName(), className, fields) }
}

def generate(out, tableName, className, fields) {
    Set types = new HashSet()

    fields.each() {
        types.add(it.type)
    }

    out.println "package $packageName"
    out.println ""
    out.println "import com.gitee.loyo.PrimaryKey;"
    out.println "import com.gitee.loyo.act.*"
    if (types.contains("BigDecimal")) {
        out.println "import java.math.BigDecimal;"
    }
    if (types.contains("LocalDate")) {
        out.println "import java.time.LocalDate;"
    }
    if (types.contains("LocalDateTime")) {
        out.println "import java.time.LocalDateTime;"
    }
    out.println ""
    out.println "class ${className}Model ("
    fields.each() {
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "  val ${it.columnName}: ${it.columnTypeName},"
    }
    out.println "): Model<${className}Model, ${className}>(\"${tableName}\"){"
    out.println ""
    out.println "    companion object: ${className}DaoModelCompanion()"
    out.println "}"
    out.println ""
    out.println "open class ${className}DaoModelCompanion ("
    out.println "   ref: ModelCompanionRef<${className}Model, ${className}> = ModelCompanionRef()"
    out.println "): ModelCompanion<${className}Model, ${className}>(ref)"
    out.println ""

    out.println "data class ${className} ("
    fields.each() {
        out.println "  var ${it.name}: ${it.type}? = null,"
    }
    out.println "): ${className}DaoRecord()"
    out.println ""
    out.println "open class ${className}DaoRecord ("
    out.println "   ref: RecordRef<${className}Model, ${className}> = RecordRef()"
    out.println "): Record<${className}Model, ${className}>(ref)"
    out.println ""
}

def calcFields(table) {
  def primaryKeys = DasUtil.getPrimaryKey(table).getColumnsRef().names()
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 name : javaName(col.getName(), false),
                 type : typeStr,
                 columnName: col.getName().toString().toLowerCase(),
                 columnType: col.getDataType(),
                 columnTypeName: col.getDataType().typeName.toUpperCase(),
                 annos: primaryKeys.contains(col.getName().toString()) ? "@PrimaryKey" : ""]]
  }
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
    .collect { Case.LOWER.apply(it).capitalize() }
    .join("")
    .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
